package com.lgs7907.simplestockinfo;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

//BitmapDownloaderTask task = new BitmapDownloaderTask(new BitmapDownloaderTask.ICallback() {
//	@Override
//	public void afterPost(Bitmap bitmap, String idString) {
//		if (bitmap != null) {
//			imageView.setImageBitmap(bitmap);
//		}
//	}
//});
//task.execute(imageUrl, "");

public class BitmapDownloaderTask extends AsyncTask<String, Void, Bitmap> {
	private ICallback callback;
	private String idString;

	public BitmapDownloaderTask(ICallback iCallback) {
		this.callback = iCallback;
	}

	@Override
	protected Bitmap doInBackground(String... params) { // 实际的下载线程，内部其实是concurrent线程，所以不会阻塞
		idString = params[1];
		return downloadBitmap(params[0]);
	}

	public Bitmap downloadBitmap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			Log.e("mhs", "downloadBitmap get url err: " + e.getMessage());
			// e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			Log.e("BitmapDownloaderTask", "远程图片不存在: " + e.getMessage());
			// e.printStackTrace();
		}
		return bitmap;
	}

	@Override
	protected void onPostExecute(Bitmap bitmap) { // 下载完后执行的
		if (isCancelled()) {
			bitmap = null;
		}
		callback.afterPost(bitmap,idString);
	}

	public interface ICallback {
		public void afterPost(Bitmap bitmap,String id);
	}
}